# -*- coding: utf-8 -*-

import funcy as F
import configparser
import style

from   plumbum import FG
import plumbum
import plumvgr


DOIT_CONFIG = {'default_tasks': ['plumvgr']}
# DOIT_CONFIG = {'action_string_formatting': 'old' or 'new' or 'both'}
# DOIT_CONFIG = {'verbosity': 2}

vagrant_machine = None


def readcfg():
	cfg = configparser.ConfigParser()
	assert cfg.read('etc/doit.cfg') == ['etc/doit.cfg']
	return cfg

cfg = readcfg()


def task_up():
	"""vagrant up"""

	cwd = cfg.get('k3s-barge', 'directory')

	def vagrant_up(dryrun):
		if not dryrun:
			lines = plumbum.cmd.vagrant['up', '--machine-readable'].popen(cwd=cwd)
			lines = F.filter(None, F.flatten(lines))
			for line in lines:
				_, vm, key, *args = line.split(',')
				if vm == '' and key == 'ui' and 1 < len(args):
					value = ' '.join(args[1:])
					print(style.light_black('  ', value.strip()))

	def check_up():
		lines = plumbum.cmd.vagrant['status', '--machine-readable'].popen(cwd=cwd)  # [(out, err)]
		lines = F.filter(None, F.flatten(lines))
		result = True
		for line in lines:
			_, vm, key, *args = line.split(',')
			value = ' '.join(args)
			if key == 'state' and value != 'running':
				result = result and False
			if key == 'state-human-short':
				# $ bin.doit -v2 ...
				print(style.light_black('   {}: {}'.format(vm, value)))
#		assert result
		return result

	return {
		'actions' : [vagrant_up],
		'uptodate': [check_up],
		'params'  : [{
			'name'   : 'dryrun',
			'long'   : 'dryrun',
			'short'  : 'n',
			'type'   : bool,
			'default': False,
			'help'   : 'perform a trial run with no changes made'}],
	}


def task_nodes():
	"""simple example"""

	def vagrant_ssh():
		# vagrant_machine <- setup
		lines = vagrant_machine.cmd.kubectl['get', 'nodes'].popen()
		lines = F.filter(None, F.flatten(lines))
		for line in lines:
			# $ bin.doit -v2 nodes
			print(style.light_black('  ', line))

	return {
		'actions' : [vagrant_ssh],
		'task_dep': ['up'],
		'setup'   : ['_vagrant_machine'],
	}


def task__vagrant_machine():
	cwd = cfg.get('k3s-barge', 'directory')

	def setup():
		global vagrant_machine
		assert vagrant_machine is None, vagrant_machine
		vagrant_machine = plumvgr.VagrantMachine(vmdir=cwd, vmname='master')

	def teardown():
		global vagrant_machine
		if vagrant_machine is not None:
			vagrant_machine.close()
			vagrant_machine = None

	return {
		'actions' : [setup],
		'teardown': [teardown]}
